<?php
namespace app\index\model;

use think\Model;
use think\Db;

class Redpacket extends Model
{
    
    /**
     * 判断用户今天是否已经获取每日红包 
     * @param  int $user_id 必填, 用户的id
     * @return Boolean
     */
    public function isGetDailyRedpacket($user_id){
        //获取今日开始时间与结束时间 
        $beginToday = mktime(0,0,0,date('m'),date('d'),date('Y'));
        $endToday   = mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;

        return db('User_redpacket')->where('user_id',$user_id)->where('get_time','between',"$beginToday,$endToday")->find() ? true : false ;

    }

	/**
     * 赠送用户红包
     *
     * @param int $user_id 必填, 用户的id
     * @param int $redpacket_id 必填，红包的id
     * @return status
     */
	public function giveUserRedpacket($user_id,$redpacket_id,$price){
		$insert_info['user_id']      = $user_id;
		$insert_info['redpacket_id'] = $redpacket_id;
		$insert_info['get_time']     = time();
        $insert_info['price']        = $price;
        
        //获取红包获取的状态
        if(db('redpacket')->where('id',$redpacket_id)->value('status')){
            return db('user_redpacket')->insert($insert_info);
        }
	}
    
    /**
     * 获取用户的红包列表
     *
     * @param int $user_id 必填, 用户的id
     * @return array
     */
    public function getUserRedpacketList($user_id){
    	$sql = "select ur.id,r.name,ur.price,r.rule_description,ur.status,ur.use_time from sc_user_redpacket ur left join sc_redpacket r on ur.redpacket_id = r.id where ur.user_id = $user_id order by ur.status asc,ur.get_time desc";
    
        return Db::query($sql);
    }

    /**
     * 获取用户未使用的红包数量
     *
     * @param int $user_id 必填, 用户的id
     * @return array
     */
    public function getUserRedpacketCount($user_id){
    	$where['user_id'] = $user_id;
    	$where['status']  = 0;
    	return db('user_redpacket')->where($where)->count();
    }

    /**
     * 用户使用红包
     *
     * @param int $user_id 必填, 用户的id
     * @param int $redpacket_id 必填, 红包的id
     * @return array
     */
    public function userUseRedPacket($id){
        $User_redpacket        = db('user_redpacket');

        $where['id'] = $id;

        $update_info['status']   = 1;
        $update_info['use_time'] = time(); 

        $result = $User_redpacket->where($where)->update($update_info);
        
        if($result === 0 || $result){
            return $User_redpacket->where('id',$id)->value('price');
        }else{
            return -1;
        }
       
    }


}